<template>
  <div class="jax-desc">
    <div class="jax-desc-header">
      <div class="jax-desc-title" v-if="title">{{ title }}</div>
      <!-- <div class="jax-desc-extra"></div> -->
    </div>
    <div class="jax-desc-body">
      <template v-if="modelValue && jsonList">
        <jax-desc-item v-for="(item, index) in jsonList" :key="index" :label="item.label">
          <template v-if="$slots[item.name]">
            <slot :name="item.name"></slot>
          </template>
          <template v-else>{{ item.value || modelValue[item.name] }}</template>
        </jax-desc-item>
      </template>
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'jax-desc',
  provide() {
    return {
      jaxDesc: this,
    }
  },
  props: {
    // 表单数据v-model
    modelValue: null,

    // 表单结构
    json: {
      type: Array,
      default: [],
    },

    // 标题
    title: {
      type: String,
    },

    // 标签宽度
    labelWidth: {
      default: '100px',
    },

    // 一行 desc-item 的数量
    column: {
      type: Number,
      default: 1,
    },
  },
  computed: {
    columnWidth() {
      return `${100 / this.column}%`
    },
  },
  data() {
    return {
      jsonList: null,
    }
  },
  watch: {
    json() {
      this.jsonList = this.extractToList(this.json)
    },
  },
  created() {
    this.jsonList = this.extractToList(this.json)
  },
  methods: {
    /**
     * 把json中的多维数据提取成一维数据列表，并计算span大小
     */
    extractToList(data, span = 24) {
      let list = []

      data.map((item) => {
        if (Array.isArray(item)) {
          const newList = this.extractToList(item, 24 / item.length)
          list = list.concat(newList)
        } else {
          list.push(item)
          // list.push({
          //   span: item.span || span,
          //   options: item,
          // })
        }
      })

      return list
    },
  },
}
</script>

<style></style>
